package com.hcb.tonguetiphealth.widget.citywide;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.hcb.tonguetiphealth.adapter.CityWideActivitysListAdapter;
import com.hcb.tonguetiphealth.global.Global;
import com.hcb.tonguetiphealth.manager.JSONManager;
import com.hcb.tonguetiphealth.model.CityActivity;
import com.hcb.tonguetiphealth.model.User;
import com.hcb.tonguetiphealth.util.HttpUtils;
import com.hcb.tonguetiphealth.util.MessageWhat;
import com.hcb.tonguetiphealth.util.StringUtils;
import com.hcb.tonguetiphealth.view.AbstractActivity;
import com.hcb.tonguetiphealth.view.R;
import com.hcb.tonguetiphealth.widget.GeneralWidget;

public class CityWideWidget extends GeneralWidget implements OnClickListener {
	private static final long REFRESH_TIMER = 1000 * 5;
	private Activity ctx;
	private TextView tvCommit;
	private LinearLayout llBack;
	private Handler mHandler;
	private List<CityActivity> cityActivityList;
	private CityWideActivitysListAdapter adapter;
	private ListView cityActivityListView;
	private String count = "0";
	private String cityId;
	
	private View footerView;
	private TextView tv_footerMore;
	private ProgressBar pb_footerMore;

	private List<CityActivity> cityTopActivityList;
	private int lastPosition = -1;
	private int topCount;
	private TimerTask refreshTimerTask;
	private Timer timer;
	private boolean isTimerStarted = false; 
	private boolean isFirst = true;
	
	public CityWideWidget(Context context) {
		super(context);
		ctx = (Activity) context;
		inflate(context, R.layout.city_wide, this);
		//new BottomWidget(ctx, this);
		bindView();
		bindEvent();
		cityActivityList =  new ArrayList<CityActivity>();
		cityTopActivityList =  new ArrayList<CityActivity>();
		adapter = new CityWideActivitysListAdapter(ctx,
				cityActivityList, mHandler);
		cityActivityListView.setAdapter(adapter);
		
		initData();
		getData();
	}

	private void bindView() {
		llBack = (LinearLayout) findViewById(R.id.city_wide_back);
		tvCommit = (TextView) findViewById(R.id.city_wide_commit_textview);
		cityActivityListView = (ListView) findViewById(R.id.city_wide_listview);
		
		footerView = LayoutInflater.from(ctx).inflate(R.layout.refresh_list_footer, null);
		tv_footerMore = (TextView)footerView.findViewById(R.id.refresh_list_footer_text);
		pb_footerMore = (ProgressBar)footerView.findViewById(R.id.refresh_list_footer_progressbar);
		cityActivityListView.addFooterView(footerView);
	}

	private void bindEvent() {
		llBack.setOnClickListener(this);
		tvCommit.setOnClickListener(this);
		
		mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case MessageWhat.SHOW_DIALOG:
					showMessageDialog(ctx, "正在发送请求...");
					break;
				case MessageWhat.DIMISS_DIALOG:
					if (msg.obj != null) {//发送短信请求处理
						String reqSucess = (String)msg.obj;
						System.out.println("reqsucessL==========="+reqSucess);
						if(reqSucess.equals("true")){
							showMessage(ctx, "短信发送成功，请稍后查收！");
						}else {
							showMessage(ctx, "请求失败，请稍后重试！");
						}
					}
					
					break;
				case MessageWhat.FAILD:
					tv_footerMore.setText(R.string.app_list_footer_more_text);
					pb_footerMore.setVisibility(ProgressBar.GONE);
					dismissMessageDialog();
					break;
				case MessageWhat.SUCCEED:
					//----------------------------------------------------------  
				        Calendar calendar = Calendar.getInstance();
				        long now = calendar.getTimeInMillis();//获得当前时间的毫秒表示
				        calendar.set(2013, 4, 28, 0, 0, 0);
				        long end = calendar.getTimeInMillis();
				        if(now > end) {
				        	cityTopActivityList.clear();
				        }
			        //----------------------------------------------------------
					if(isFirst) {
						isFirst = false;
						if(cityTopActivityList.size() > 3) {
							topCount = 3;
							startTimer();
						} else {
							topCount = cityTopActivityList.size();
						}
						for(int i=0; i<topCount; i++) {
							cityActivityList.add(i, cityTopActivityList.get(getLastPosition() % cityTopActivityList.size()));
						}
					} else {
						if(cityTopActivityList.size() > topCount && topCount < 3) {
							int tCount = topCount;
							if(cityTopActivityList.size() > 3) {
								topCount = 3;
								startTimer();
							} else {
								topCount = cityTopActivityList.size();
							}
							for(int i=tCount; i<topCount; i++) {
								cityActivityList.add(i, cityTopActivityList.get(getLastPosition() % cityTopActivityList.size()));
							}
						}
						if(cityTopActivityList.size() > 3 && !isTimerStarted) {
							startTimer();
						}
					}
					adapter.setTopCityActivityListSize(cityTopActivityList.size());
					adapter.notifyDataSetChanged();
					tv_footerMore.setText(R.string.app_list_footer_more_text);
					pb_footerMore.setVisibility(ProgressBar.GONE);
					dismissMessageDialog();
					break;
				case MessageWhat.START_TIMER:
					startTimer();
					break;
				case MessageWhat.CANCEL_TIMER:
					cancelTimer();
					break;
				case MessageWhat.FRESH_TOP_ACTIVITY:
					System.out.println("------------------------ 置顶活动刷新 ");
					if(cityTopActivityList.size() > 3) {
						cityActivityList.set(0, cityTopActivityList.get(getLastPosition() % cityTopActivityList.size()));
						cityActivityList.set(1, cityTopActivityList.get(getLastPosition() % cityTopActivityList.size()));
						cityActivityList.set(2, cityTopActivityList.get(getLastPosition() % cityTopActivityList.size()));
					} else {
						for(int i=0; i<cityTopActivityList.size(); i++) {
							cityActivityList.set(i, cityTopActivityList.get(getLastPosition() % cityTopActivityList.size()));
						}
					}
					
					adapter.notifyDataSetChanged();
					startTimer();
					break;
				case MessageWhat.NETWORK_FAILD:
					try {
						dismissMessageDialog();
						tv_footerMore.setText(R.string.app_list_footer_more_text);
						pb_footerMore.setVisibility(ProgressBar.GONE);
					} catch (Exception e) {
						// TODO: handle exception
					}
					// Toast.makeText(ctx, "网络有点不给力哦",
					// Toast.LENGTH_LONG).show();
					showMessage(ctx, R.string.net_faild);
					
					break;
				case MessageWhat.LOGIN:
					login();
					break;
				}
			}
		};
		footerView.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				tv_footerMore.setText(R.string.app_list_footer_getting_text);
				pb_footerMore.setVisibility(ProgressBar.VISIBLE);
				getData();
			}
		});
	}
	private int getLastPosition() {
		lastPosition ++;
		if(lastPosition >= cityTopActivityList.size()) {
			lastPosition = 0;
		}
		return lastPosition;
	}

	private void getData() {
		mHandler.sendEmptyMessage(MessageWhat.SHOW_DIALOG);
		count = cityActivityList.size() + cityTopActivityList.size() +"";
		new Thread() {
			public void run() {
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("cityId", cityId));
				params.add(new BasicNameValuePair("count", count));
				String respone = HttpUtils.Post(Global.getServletactivitys(), params);
				System.out.println("-------------------------------\n " + respone);
				if (respone != null) {
					JSONManager jsonManager = new JSONManager();
					if (jsonManager.isGotJSONObject(respone)) {
						JSONArray jsonArray = jsonManager.getJsonList();
						CityActivity activity;
						String isTop;
						for (int i = 0, len = jsonArray.length(); i < len; i++) {
							JSONObject obj;
							activity = new CityActivity();
							try {
								obj = jsonArray.getJSONObject(i);
								User user = new User();
								user.setUserId(getString(obj, "userid"));
								user.setUserName(getString(obj,"username"));
								user.setImgUrl(getString(obj, "headicon"));
								activity.setUser(user);
								activity.setType(StringUtils.parseInt(getString(obj, "activityType")));
								activity.setAddTime(StringUtils.parseLong(getString(obj, "addtime")));
								activity.setId(getString(obj, "itemid"));
								activity.setCityId(getString(obj, "cityid"));
								activity.setActivityName(getString(obj, "activity"));
								activity.setActivityAddress(getString(obj, "address"));
								activity.setActivityIntro(getString(obj, "intro"));
								activity.setPeopleNum(StringUtils.parseInt(getString(obj, "number") ) );
								activity.setTel(getString(obj, "tel"));
								isTop = getString(obj, "topType");
								if(isTop != null && (isTop.equals("1") || isTop.equals("2"))) {
									activity.setTop(true);
								}
								
								if(activity.isTop()) {
									cityTopActivityList.add(activity);
								} else {
									cityActivityList.add(activity);
								}
								
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}

						}
						mHandler.sendEmptyMessage(MessageWhat.SUCCEED);
					} else {
						mHandler.sendEmptyMessage(MessageWhat.FAILD);
					}
				} else {
					mHandler.sendEmptyMessage(MessageWhat.NETWORK_FAILD);
				}
			}
		}.start();
	}

	private void initData() {
		SharedPreferences preferences = ctx.getSharedPreferences(Global.CITYID,
				0);
		cityId = preferences.getString(Global.CITYID, Global.defaultCityId);
	}
	@Override
	public void notifyAdapter() {

	}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		switch (arg0.getId()) {
		case R.id.city_wide_back:
			ctx.finish();
			break;
		case R.id.city_wide_commit_textview:
			cancelTimer();
			ctx.setContentView(new CityWideCommitWidget(ctx));
			break;
		default:
			break;
		}
	}
	private void startTimer() {
		isTimerStarted = true;
		AbstractActivity.setHandler(mHandler);
		refreshTimerTask = new TimerTask() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				mHandler.sendEmptyMessage(MessageWhat.FRESH_TOP_ACTIVITY);
			}
		};
		 timer = new Timer();
        timer.schedule(refreshTimerTask, REFRESH_TIMER);
	}
	private void cancelTimer() {
		if(timer != null) {
			timer.cancel();
		}
	}
}
